import { View, Input, Textarea, Image, Button } from '@tarojs/components';
import { DatePicker } from '@nutui/nutui-react-taro';
import { useState } from 'react';
import { useSelector } from 'react-redux';
import { RootState } from '@/store';
import { AddressType, goToFillAddress } from '@/utils/address';
import { getUser } from '@/utils/user';
import './index.less';
import Taro from '@tarojs/taro';
import request from '@/utils/request';
import { IOrder } from '@/types/order';

// 计算价格函数
const calculatePrice = (date: string, dateEnd: string) => {
  if (!dateEnd) return 2; // 只选一天，按2元/天
  const date1 = new Date(date);
  const date2 = new Date(dateEnd);
  // 计算天数，包含首尾两天
  let diffDays = Math.abs(Math.floor((date2.getTime() - date1.getTime()) / (1000 * 60 * 60 * 24))) + 1;
  if (diffDays <= 6) {
    return diffDays * 2;
  } else if (diffDays >= 7 && diffDays <= 29) {
    return diffDays * 1;
  } else if (diffDays >= 30) {
    return diffDays * 0.5;
  }
  return 2;
}

export default function Index() {
  const user = getUser();
  const { fullAddress = "" } = useSelector((state: RootState) => state.address);
  const [date, setDate] = useState(() => {
    const today = new Date();
    return `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`;
  });
  const [dateEnd, setDateEnd] = useState('');
  const [showPicker, setShowPicker] = useState(false);
  const [showPicker2, setShowPicker2] = useState(false);
  const [phone, setPhone] = useState(user?.phone||'');
  const [remark, setRemark] = useState('');

  const handlePublish = () => {
    // 处理发布逻辑
    // console.log('phone', phone);
    // 判断信息是否填写完整
    if(!date){
      Taro.showToast({
        title: '请选择时间',
        icon: 'none',
      });
      return;
    }
    if(fullAddress?.length <= 5){
      Taro.showToast({
        title: '请设置居住地址',
        icon: 'none',
      });
      return;
    }
    const createOrder = async () => {
      const orderAmount = calculatePrice(date, dateEnd);
      const order = await request.post<IOrder>('/order/create', {
        orderAmount: orderAmount,
        userId: user?.id,
        orderType: "trash",
        desc: remark,
        time: date,
        timeEnd: dateEnd,
        fullAddress: fullAddress,
      });
      console.log("order",order);
      if(order?.id){
        // 构建跳转URL
        let url = `/pages/order-review/index?price=${orderAmount}&orderId=${order?.id}&time=${date}`;
        if (dateEnd) {
          url += `&timeEnd=${dateEnd}`;
        }
        // 跳转到order-review页面
        Taro.navigateTo({ url });
      }
    }
    createOrder();
  };

  const handleDateConfirm = (value: Array<string | number>) => {
    // 如果value是number，使用"YYYY-MM-DD"日期格式转化成string
    const date = value.join("-");
    setDate(date);
    setShowPicker(false);
  };

  const handleDateConfirm2 = (value: Array<string | number>) => {
    const date = value.join("-");
    setDateEnd(date);
    setShowPicker2(false);
  };

  return (
    <View className="take-trash">
      <View className="content">
        {/* <Image 
          className="banner"
          src="https://your-image-url.com/rules.png" // 需要替换为实际的图片地址
          mode="widthFix"
        /> */}

        <View className="form">
          <View className="form-item">
            <View className="label">开始时间</View>
            <Input 
              className="input"
              type="text"
              value={date}
              placeholder="请选择您需要的时间"
              placeholderClass="placeholder"
              disabled
              onClick={() => setShowPicker(true)}
            />
          </View>
          <View className="form-item">
            <View className="label">结束时间</View>
            <Input 
              className="input"
              type="text"
              value={dateEnd}
              placeholder="请选择您需要的时间"
              placeholderClass="placeholder"
              disabled
              onClick={() => setShowPicker2(true)}
            />
          </View>

          <View className="form-item">
            <View className="label">价格：<View className="price">{calculatePrice(date, dateEnd)} 元</View></View>
          </View>

          <View className="form-item">
            <View className="label">居住地址</View>
            <View className="address-wrapper">
              <Input 
                className="input"
                type="text"
                value={fullAddress}
                disabled
                placeholder="请先设置您的居住地址"
                placeholderClass="placeholder"
              />
              <Button 
                className="btn-edit-address" 
                onClick={()=>{
                  goToFillAddress(AddressType.BACK);
                }}
              >
                修改
              </Button>
            </View>
            <View className="tip">手动修改住址变更可至「我的-居住地址」中更新</View>
          </View>

          <View className="form-item">
            <View className="label">手机号</View>
            <Input 
              className="input"
              type="number"
              value={phone}
              onInput={e => setPhone(e.detail.value)}
              placeholder="请输入您的手机号"
              placeholderClass="placeholder"
            />
          </View>

          <View className="form-item">
            <View className="label">备注</View>
            <Textarea
              className="textarea"
              value={remark}
              onInput={e => setRemark(e.detail.value)}
              placeholder="请填写备注信息"
              placeholderClass="placeholder"
            />
          </View>
        </View>
      </View>

      <View className="footer">
        <Button 
          className="btn btn-publish" 
          onClick={handlePublish}
        >
          <View className="button-content">
            <View className="text">发布</View>
          </View>
        </Button>
      </View>

      <DatePicker
        visible={showPicker}
        type="date"
        onClose={() => setShowPicker(false)}
        onConfirm={(_, value) => {
          handleDateConfirm(value);
        }}
        startDate={new Date()}
      />
      <DatePicker
        visible={showPicker2}
        type="date"
        onClose={() => setShowPicker2(false)}
        onConfirm={(_, value) => {
          handleDateConfirm2(value);
        }}
        startDate={new Date(date)}
      />
    </View>
  );
}
